package cn.school.controller.pay;



import cn.school.app.service.TuitionPaymentService;
import cn.school.common.api.CommonResult;
import cn.school.common.utils.SysUserUtils;
import cn.school.pay.service.PayOrderInfoService;
import cn.school.pay.vo.ChargeItemVO;
import cn.school.pay.vo.PayOrderInfoVO;
import cn.school.student.entity.StudentInfo;
import com.alipay.api.AlipayApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 在线支付控制器
 */
@RestController
@RequestMapping("/pay/")
public class OnlinePayController {

    @Autowired
    private PayOrderInfoService payOrderInfoService;
    @Resource
    TuitionPaymentService tuitionPaymentService;
    /**
     * 生成支付订单
     * @return 订单map
     */
    @PostMapping("/createPayOrder")
    public CommonResult<Map<String,Object>> createPayOrder(@RequestBody PayOrderInfoVO vo) throws AlipayApiException, UnsupportedEncodingException {
        StudentInfo uservo = SysUserUtils.getStudentUser();
        if(StringUtils.isEmpty(vo.getAmount()) || StringUtils.isEmpty(vo.getPayPlatform())){
            return CommonResult.failed("缺少必要参数");
        }
        List<ChargeItemVO> itemList =  tuitionPaymentService.findStudentTuition();
        BigDecimal amount = BigDecimal.ZERO;
        for (ChargeItemVO itemVO : itemList){
            amount = amount.add(itemVO.getChargeAmount());
        }
        if(vo.getAmount().compareTo(amount)!=0){
            return CommonResult.failed("订单金额异常。");
        }
        vo.setCreateBy(String.valueOf(uservo.getId()));
        Map<String,Object> map = payOrderInfoService.createPayOrder(vo);

        return CommonResult.success(map);
    }

    /**
     * 第一步:验证签名,签名通过后进行第二步 第二步:按一下步骤进行验证
     * 验证app_id是否为该商户本身。上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
     * 在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，并且过滤重复的通知结果数据。
     * 在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。
     *
     * @throws AlipayApiException
     */
    @RequestMapping("/aliNotifyCallbackPayOffline")
    @ResponseBody
    public String aliNotifyCallbackPayOffline(HttpServletRequest request) throws AlipayApiException {
        Map requestParams = request.getParameterMap();
        System.out.println(requestParams);
        Map<String,String> params = new HashMap<String,String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return payOrderInfoService.aliNotifyCallbackPayOffline(params);
    }
}
